package org.abettor.pushbox.download;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.pushbox.model.NotifyBean;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

public class ParaNotify {
	/**
	 * 解析最后一次更新的时间
	 * @param content
	 * @return
	 */
	public static Date paraLastDate(String content){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes());
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(in);
			NodeList list = doc.getElementsByTagName("t");
			Node node = list.item(0);
			String value = node.getFirstChild().getNodeValue();
			return sdf.parse(value);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 解析更新的bean
	 * @param content
	 * @return
	 */
	public static List<NotifyBean> paraNotifyBean(String content){
		ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes());
		List<NotifyBean> retList = new ArrayList<NotifyBean>();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(in);
			NodeList list = doc.getElementsByTagName("v");
			for (int i = 0; i < list.getLength(); i++) {
				NotifyBean bean = new NotifyBean();
				Node node = list.item(i);
				NodeList nodes = node.getChildNodes();
				// 解析id
				int count = nodes.getLength();
				for (int j = 0; j < count; j++) {
					Node pairNode = nodes.item(j);
					String nodeName = pairNode.getNodeName();
					String tmp = pairNode.getFirstChild().getNodeValue();
					if ("id".equals(nodeName)) {
						bean.setId(tmp);
					} else if ("ty".equals(nodeName)) {
						bean.setType(Integer.parseInt(tmp));
					}
				}
				retList.add(bean);
			}
			in.close();
			return retList;
		} catch (Exception e) {
			Log.e(ParaDownloadRetValue.class.getName(), "", e);
			return null;
		}
	}
}
